<template>
  <t-dialog
    header="上传资质文件至媒体库"
    :width="width ? width : '60vw'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    :footer="false"
    preventScrollThrough
    placement="center"
  >
    <t-form>
      <t-form-item label="文件说明" help="备注将与文件一并上传，如需备注，请输入备注后选择文件，点击上传即可。">
        <t-input v-model="uploadFileRemark" maxlength="100" />
      </t-form-item>
      <t-form-item label="文件上传">
        <t-upload
          theme="file-flow"
          :withCredentials="true"
          :auto-upload="true"
          :multiple="false"
          :request-method="handleFileUpload"
          :max="1"
        />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { ref } from "vue";

// API
import { uploadFileMany } from "@/api/file";

defineProps(["width", "showDialog"]);

const emits = defineEmits(["onClose", "onConfirm"]);

const uploadFileRemark = ref("");
const handleFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData, uploadFileRemark.value);
    if (res.code === 200) {
      emits("onConfirm", res);
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleCancel = () => {
  emits("onClose", "cancel");
};

const handleConfirm = () => {};
</script>
